class GridEvent < ActiveRecord::Base

  unloadable #can't dup NilClass in task_scheduler.rb fix

  belongs_to :grid

  def self.create_event(event_name, data, grid)
    version = grid.version + 1
    grid.update_attribute(:version, version)
    self.create!(:data => {:data => [event_name, data.to_hash, version]}.to_json, :grid => grid, :version => version)
  end

  def self.to_json(events)
    "[#{events.collect {|event| event.data}.join(', ')}]"
  end

  def self.find_waiting_events(grid_id, version)
    self.find_by_sql ['select * from grid_events where grid_id = ? and version > ? order by version', grid_id, version]
  end

end
